<%@ page pageEncoding="UTF-8"%>
<%@ page import="java.util.Map.Entry,java.util.*,java.util.regex.*,java.net.*,java.io.*,java.text.*"%>
<%@ page import="com.tianxiabuyi.*,com.tianxiabuyi.persist.*,com.tianxiabuyi.model.pojo.*,com.tianxiabuyi.utils.*"%>
<%@ page import="com.alibaba.fastjson.TypeReference" %>
<%@ include file = "user.jsp"%>
<%@ include file = "operatehistory.jsp"%>
<%!
	// 问题列表
	Message quests(Input input) {
		return search(input);
	}

	// 我的问题列表
	Message my(Integer uid, Input input) {
		input.setDesc("uuid", uid + "");
		input.setDesc("uid", uid + "");
		input.setDesc("range", "my");
		return search(input);
	}

	// 搜索问题列表
	Message search(Input input) {
		Integer page = 1;
		Integer itemCount = input.getInt("item_count", 20);
		Integer groupId = input.getInt("group", -1); // 分组id, 默认全部分类问题
		Integer uid = input.getInt("uid", -11); // 访问用户的id
		Integer uuid = input.getInt("uuid", -11); // 用户id
		String labelId = input.getDesc("label_id", "-1");
		Integer hospital = input.getInt("hospital", -1); // 医院id
		String sinceID = input.getDesc("since_id","0"); // 下拉刷新
		String maxID = input.getDesc("max_id","0"); // 上拉加载
		String keywords = input.getDesc("keywords", ""); // 上拉加载
		String table = "Quest as q";
		Where where = new Where( groupId == -1?"":("q.groupId=" + groupId));
		if (!"-1".equals(labelId)) {
			table = table + ", LabelRelation as lr";
			where.and("lr.labelId in (" + labelId + ")").and("lr.targetId=q.id");
		}
		if (!"".equals(keywords)) {
			where.and(" q.title like '%" + keywords + "%' or q.content like '%" + keywords + "%'");
		}
		String range = input.getDesc("range", "");
		if ("my".equals(range)) {
			where.and("q.uid=" + uuid);
		}
		// 天下专家使用,查看所关注所有科室的所有医生发的帖子
		if ("doctor".equals(range)) {
			table = table + ", User as u";
			List<Integer> hospitalList = QBuilder.db("basedb").select("h.hospital").from("OperateHistory as o, Hospital as h").where(new Where("o.oid=h.id").and("o.uid=", uid).and("o.status=", STATUS_ENABLE).and("h.status=", STATUS_ENABLE).and("o.category=", DEPT_CATEGORY).and("o.operate=", ATTENTION)).query().getResultObj();
			String hospitals = "";
			for (Integer hospitalId:hospitalList) {
				hospitals = hospitals + "," + hospitalId;
			}
			hospitals = hospitals.replaceFirst(",", "");
			hospitals = hospitals.equals("")?"-1":hospitals;
			where.and("u.type=", USER_EMPLOYEE).and("u.id=q.uid").and("u.hospital=", hospital);
		}
		// 天下专家使用,查看所关注医生发的帖子
		if ("my_doctor".equals(range)) {
			table = table + ", User as u";
			List<Integer> myDoctorList = QBuilder.db("basedb").select("u.id").from("OperateHistory as o, User as u").where(new Where("o.oid=u.id").and("o.uid=", uid).and("o.status=", STATUS_ENABLE).and("u.status=", STATUS_ENABLE).and("o.category in(" +SECTION_DOCTOR + "," + SECTION_PATIENT + ")").and("o.operate=", ATTENTION)).query().getResultObj();
			String doctorIds = "";
			for (Integer doctorId:myDoctorList) {
				doctorIds = doctorIds + "," + doctorId;
			}
			doctorIds = doctorIds.replaceFirst(",", "");
			doctorIds = doctorIds.equals("")?"-1":doctorIds;
			where.and("u.id=q.uid").and("u.id in(" + doctorIds + ")");
		}
		// 天下专家使用，查看普通用户发的帖子
		if ("patient".equals(range)) {
			table = table + ", User as u";
			where.and("u.type=", USER_PATIENT).and("u.id=q.uid");
		}
		String order = "desc"; // 排序
		String questId = "";
		String selectContent = "new map(q.id as id, q.title as title,case when q.imgs is null then '[]' else q.imgs end as imgs, q.uid as uid, q.content as content, q.cTime as create_time, q.aid as aid, q.groupId as group)";
		if (!sinceID.equals("0") && !sinceID.equals("")) {
			where.and("q.id > " + sinceID);
			order = "asc";
		} else if (!maxID.equals("0") && !maxID.equals("")) {
			where.and("q.id < " + maxID);
		}
		List<Map> questList = QBuilder.db("basedb").select(selectContent).from(table).where(where.and("q.hospital=", hospital).and("q.status = ", STATUS_ENABLE)).order("q.id", order).page(itemCount, page).query().getResultObj();
		if (order.equals("asc")) { // 上拉加载时倒序
			Collections.reverse(questList);
		}
		completeQuestUserInfo(questList, hospital, uid);
		Message msg = new Message();
		if (isEmpty(questList))
			 msg.setErrcodeAndErrmsg(30041, "没有更多了");
		msg.put("data", questList);
		return msg;
	}

	// 问题详情
	String show(Input input) {
		Message msg = new Message(0);
		Integer questId = input.getInt("id", 0);
		Integer hospital = input.getInt("hospital", -1); // 医院id
		Integer uuid = input.getInt("uid", -1); // 用户id
		String selectContent = "new map(id as id, title as title,case when imgs is null then '[]' else imgs end as imgs, uid as uid, content as content, cTime as create_time, aid as aid, groupId as group)";
		List<Map> questList = QBuilder.db("basedb").select(selectContent).from("Quest").where(new Where("hospital=", hospital).and("status = ", STATUS_ENABLE).and("id=", questId)).query().getResultObj();
		if (questList.size() == 0) {
			msg = new Message(30041, "没有找到这条问题");
			return msg.toJson();
		}
		List<Map> commentList = QBuilder.db("basedb").select("new map(id as id,case when imgs is null then '[]' else imgs end as imgs, uid as uid, content as content, cTime as create_time, parentId as parent_id, atUid as at_uid)").from("Comment").where(new Where("srcId=", questId).and("hospital=", hospital).and("category=", 1).and("status=", STATUS_ENABLE)).order("id", "asc").query().getResultObj();
		completeCommentUserInfo(commentList, hospital, uuid);
		Map data = new HashMap();
		List<Map> parentList = new ArrayList<Map>();
		Iterator<Map> iterator = commentList.iterator();
		while (iterator.hasNext()) {
			Map map =  iterator.next();
			if (map.get("parent_id") == null) {
				parentList.add(map);
				iterator.remove();
			}
		}
		for (Map pmap:parentList){
			Integer id = (Integer)pmap.get("id");
			List<Map> sub = new ArrayList<Map>();
			for (Map map:commentList) {
				if (((Integer)map.get("parent_id")).equals(id))
					sub.add(map);
			}
			pmap.put("sub", sub);
		}
		data.put("replies", parentList);
		OperateHistory oh = new OperateHistory();
		oh.setCategory(QUEST_CATEGORY);
		oh.setUid(uuid + "");
		oh.setOid(questId + "");
		oh.setOperate(SEE);
		operate(oh, false);
		completeQuestUserInfo(questList, hospital, uuid);
		Map questMap = questList.get(0);
		List<Long> commentCountList = QBuilder.db("basedb").queryHql("select count(*)  from Comment where hospital=" + hospital + " and category=" + 1 + " and srcId=" + questId + " group by srcId");
		completeOperateCount(questMap, QUEST_CATEGORY,  hospital,  uuid);
		questMap.put("comment", commentCountList.size() == 0?0:commentCountList.get(0));
		data.put("quest", questMap);
		msg.put("data", data);
		return msg.toJson();
	}

	// 获取图片的尺寸
	public  List<Map> size(String imgs) {
		List<String> urls = JSONUtil.fromJson(imgs, new TypeReference<List<String>>(){});
		if (urls == null || urls.size() == 0)
			return new ArrayList<Map>();
		String url = "";
		for (int i = 0; i < urls.size(); i++) {
			url = url + "," + urls.get(i);
		}
		if (url.startsWith(",")) {
			url = url.substring(1, url.length());
		}
		return JSONUtil.fromJson(HttpUtil.get("http://cloud.eeesys.com/file/size.php?urls=" + java.net.URLEncoder.encode(url)), new TypeReference<List<Map>>(){});
	}

	// 完善问题的信息，如发布者信息，浏览量，点赞量
	public  void completeQuestUserInfo(List<Map> questList, Integer hospital, Integer uuid) {
		// 评论 category 1为问答 2为新闻
		List<Map> commentList = QBuilder.db("basedb").queryHql("select new map(count(*) as count, srcId as src_id) from Comment where hospital=" + hospital + " and category=" + 1 + " group by srcId");
		List<Map> groupList = QBuilder.db("basedb").select("new map(id as id, name as name)").from("QuestGroup").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE)).query().getResultObj();
		List<Integer> uidList = new ArrayList<Integer>();
		for (int i = 0; i < questList.size(); i++) {
			Map quest = (Map)questList.get(i);
			Integer uid = Tools.getInt(quest.get("uid") + "", 0);
			Long createTime = Tools.getLong(quest.get("create_time") + "");
			String create_time = DateUtil.formatDateByFormat(new Date(createTime), DateUtil.DATETIME_FORMAT);
			quest.put("create_time", create_time);
			uidList.add(uid);
			quest.put("imgs", size(Tools.getDesc(quest.get("imgs"))));
		}
		// 查询用户信息
		Map<Integer, User> userMap = usersByUids(uidList);
		for (int i = 0; i < questList.size(); i++) {
			Map quest = (Map)questList.get(i);
			Integer uid = Tools.getInt(quest.get("uid") + "", 0);
			User user = userMap.get(uid);
			if (user != null) {
				String userName = user.getUserName();
				String nickName = user.getNickName();
				String name = user.getName();
				Integer type = user.getType();
				String title = user.getTitle();
				quest.put("user_name", getDisplayName(user));
				quest.put("avatar", getDefaultAvatar(user));
				quest.put("user_title", title);
				quest.put("user_type", type);
				quest.put("user_role", Tools.getDesc(user.getJson("role"), "1"));
			} 
			quest.put("comment", 0);
			for (Map commentMap:commentList) {
				if (((Integer)quest.get("id")).equals((Integer)commentMap.get("src_id"))) {
					quest.put("comment", commentMap.get("count"));
				}
			}
			quest.put("group_name", "");
			for (Map groupMap:groupList) {
				if (((Integer)quest.get("group")).equals((Integer)groupMap.get("id"))) {
					quest.put("group_name", groupMap.get("name"));
				}
			}
			quest.put("top", 0);
		}
		completeOperateCount(questList, QUEST_CATEGORY, hospital, uuid);
	}

	// 完善评论的信息，如发布者信息，浏览量，点赞量
	public void completeCommentUserInfo(List<Map> commentList, Integer hospital, Integer uuid) {
		List<Integer> uidList = new ArrayList<Integer>();
		for (int i = 0; i < commentList.size(); i++) {
		  Map comment = commentList.get(i);
		  Integer uid = Tools.getInt(comment.get("uid") + "", 0);
		  uidList.add(uid);
		  comment.put("imgs", size(Tools.getDesc(comment.get("imgs"))));
		  if (comment.get("at_uid") != null)
			uidList.add((Integer)comment.get("at_uid"));
		}
		Map<Integer, User> userMap = usersByUids(uidList);
		for (int i = 0; i < commentList.size(); i++) {
		  Map comment = (Map)commentList.get(i);
		  Long createTime = Tools.getLong(comment.get("create_time") + "");
		  String create_time = DateUtil.formatDateByFormat(new Date(createTime), DateUtil.DATETIME_FORMAT);
		  comment.put("create_time", create_time);
		  Integer uid = Tools.getInt(comment.get("uid") + "", 0);
		  Integer atUid = Tools.getInt(comment.get("at_uid") + "", 0);
		  User user = userMap.get(uid);
		  if (user != null) {
			String userName = user.getUserName();
			String nickName = user.getNickName();
			String avatar = getDefaultAvatar(user);
			String name = user.getName();
			comment.put("user_name", getDisplayName(user));
			comment.put("avatar", avatar);
			comment.put("type", user.getType());  // 用于判断回答用户的角色
			comment.put("user_title", user.getTitle());
			comment.put("user_role", Tools.getDesc(user.getJson("role"), "1"));
		  }
		  if (user == null) {
				String avatar = getDefaultAvatar(new User());
				comment.put("user_name", "未知用户");
				comment.put("avatar", avatar);
				comment.put("type", 100);  // 用于判断回答用户的角色
				comment.put("user_title", "");
				comment.put("user_role", "1");
		  }
		  user = userMap.get(atUid);
		  if (user != null) {
			String userName = user.getUserName();
			String nickName = user.getNickName();
			String avatar = getDefaultAvatar(user);
			String name = user.getName();
			comment.put("at_user_name", getDisplayName(user));
			comment.put("at_avatar", avatar);
			comment.put("at_type", user.getType());  // 用于判断@用户的角色
			comment.put("at_user_title", user.getTitle());
			comment.put("at_user_role", Tools.getDesc(user.getJson("role"), "-1"));
		  }
		}
		completeOperateCount(commentList, COMMENT_CATEGORY, hospital, uuid);
	}
%>
